﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Text;

/// <summary>
/// Summary description for Approval
/// </summary>
public class ApprovalBLL
{
    public ApprovalBLL()
	{
	}

    public String CustID {set;get;}
    public String AccountNo { set; get; }
    public String MachineID { set; get; }
    public String Type { set; get; }
    public String StaffID { set; get; }
    public DateTime StartDate { set; get; }
    public String Category { set; get; }
    public DateTime EndDate { set; get; }
    public String savingAccountNo { set; get; }
    public Decimal premiun { set; get; }

    public LinkedList<int> levels { set; get; }
    public LinkedList<int> applyInsuredIds { set; get; }
    public int ApplicationInsuranceId {set;get; }

    AccountsManager am = new AccountsManager();
    Alert alert = new Alert();

    public void approved()
    {
        ApprovalDAL dal = new ApprovalDAL
        {
            CustID = this.CustID,
            AccountNo = this.AccountNo,
            MachineID = this.MachineID,
            Type = this.Type,
            StaffID = this.StaffID,
            StartDate = this.StartDate,
            Category = this.Category,
            EndDate = this.EndDate,
            levels=this.levels,
            applyInsuredIds=this.applyInsuredIds,
            ApplicationInsuranceId=this.ApplicationInsuranceId

        };

        var gengerator = new AccountsManager();
        AccountNo = gengerator.GenerateNo("INSURANCE");

        dal.AccountNo = AccountNo;
       
        savingAccountNo = am.getInsuranceSavingAccountNo(CustID);
       
        if (this.checkSavingBalance())
        {
            dal.approved();
            am.transfer(savingAccountNo, AccountNo, premiun, "INSURANCE PAYMENT");
            alert.addAlertApplication(CustID, "Your INSURANCE application has been APPROVED.Premium amount of S$ " + premiun.ToString("#.##") + " has been deducted from your savings account.", "../product/insurance/user/insurance_statement.aspx");

        }
        else
        {

            dal.rejectApplicant(ApplicationInsuranceId);
            alert.addAlertApplication(CustID,"Your INSURANCE application has been DENIED due to INSUFFIENT balance in Saving Account.","");
        }

        
    }
    private Boolean checkSavingBalance(){
        Decimal balance = am.getSavingBalance(savingAccountNo);

        for (int i = 0; i < applyInsuredIds.Count;i++ )
        {
            int ApplicationInsuredId = applyInsuredIds.ElementAt(i);
            int level = levels.ElementAt(i);
            premiun += am.getInsurancePremium(ApplicationInsuredId, level, Category);

        }

        if (balance >= premiun)
        {
            return true;
        }else{

            return false;
        }
    }

    
}